from rest_framework import serializers
from .models import Book
from categories.serializers import CategorySerializer

class BookSerializer(serializers.ModelSerializer):
    category = CategorySerializer(read_only=True)
    category_id = serializers.IntegerField(write_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    is_available = serializers.BooleanField(read_only=True)
    current_borrowing = serializers.SerializerMethodField(read_only=True)
    borrowing_count = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'isbn', 'publisher', 'publish_date', 
                  'category', 'category_id', 'description', 'cover_image', 
                  'page_count', 'language', 'status', 'status_display', 
                  'is_available', 'location', 'current_borrowing', 
                  'borrowing_count', 'created_at', 'updated_at']
        read_only_fields = ['id', 'created_at', 'updated_at', 'status_display', 'is_available']

    def get_current_borrowing(self, obj):
        """获取当前借阅信息"""
        borrowing = obj.get_current_borrowing()
        if borrowing:
            return BorrowingSerializer(borrowing).data
        return None

    def get_borrowing_count(self, obj):
        """获取借阅次数"""
        return obj.borrowings.count()

    def validate(self, data):
        """验证图书数据"""
        # 检查ISBN是否已存在（排除当前图书）
        isbn = data.get('isbn')
        if isbn and self.instance:
            if Book.objects.exclude(id=self.instance.id).filter(isbn=isbn).exists():
                raise serializers.ValidationError("该ISBN已存在")
        elif isbn and Book.objects.filter(isbn=isbn).exists():
            raise serializers.ValidationError("该ISBN已存在")
        return data

class BookListSerializer(serializers.ModelSerializer):
    """图书列表序列化器，只包含必要信息"""
    category = serializers.StringRelatedField(read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    is_available = serializers.BooleanField(read_only=True)

    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'isbn', 'category', 
                  'status', 'status_display', 'is_available', 'cover_image']

